//
//  LDSRegisterTableCell.m
//  TestCategory
//
//  Created by kai_leedarson on 2017/10/19.
//Copyright © 2017年 maple_leedarson. All rights reserved.
//

#import "LDSRegisterTableCell.h"
#import "LDSRegisterModel.h"
#define kTimeCount 60
static int sendValidateCodeTimeCount = 0;
@interface LDSRegisterTableCell ()
@property(nonatomic, strong) dispatch_source_t timer;
@end

@implementation LDSRegisterTableCell

- (void)viewSetup {
    self.backgroundColor = [UIColor clearColor];
    self.backView.layer.masksToBounds = YES;
    [self.rightButton addTarget:self action:@selector(rightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)frameSetup {
    self.backView.layer.cornerRadius = 27.0f;
}

- (void)setModel:(LDSRegisterModel *)model
{
    [super setModel:model];
    if (model) {
        //将model 的数值 传递给 cell
        self.textField.placeholder = model.text;
        self.avatar.image = [UIImage imageNamed:model.imageName];
        if ([model.text isEqualToString:@"Verification code"]) {
            self.rightButton.hidden = NO;
        } else {
            self.rightButton.hidden = YES;
        }
    }
}

+ (CGFloat)height {
    return 70.0f;
}

- (void)rightButtonClicked:(UIButton *)sender {
    [self initSendValidateCodeCount];
}

- (void)initSendValidateCodeCount {
    __weak __typeof(self)weakSelf = self;
    sendValidateCodeTimeCount = kTimeCount;
    weakSelf.rightButton.enabled = NO;
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 1));
    dispatch_source_set_timer(self.timer, dispatch_time(DISPATCH_TIME_NOW, 0), 1 * NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(self.timer, ^{
        sendValidateCodeTimeCount --;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *title = [NSString stringWithFormat:@"%lds",(long)sendValidateCodeTimeCount];
            [weakSelf.rightButton setTitle:title forState:UIControlStateNormal];
            if (sendValidateCodeTimeCount == 0) {
                dispatch_suspend(weakSelf.timer);
                weakSelf.rightButton.enabled = YES;
                [weakSelf.rightButton setTitle:@"get Code"
                                        forState:UIControlStateNormal];
            }
        });
    });
    dispatch_resume(weakSelf.timer);
}

@end
